<?php

namespace app\controller\api;

use app\model\OrderModel;
use app\model\OrderItemModel;
use app\model\OrderRefundModel;
use app\model\ProductModel;
use app\model\ProductSkuModel;
use support\Request;
use support\Response;
use app\exception\BusinessException;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("订单接口")
 * @Apidoc\Group("api")
 */
class OrderController
{
    /**
     * 创建订单
     */
    public function create(Request $request)
    {
        $user = $request->user;
        $data = $request->post();
        
        // 验证订单数据
        $this->validateOrderData($data);
        
        try {
            \DB::beginTransaction();
            
            // 创建订单
            $order = new OrderModel();
            $order->order_no = $this->generateOrderNo();
            $order->user_id = $user->id;
            $order->shipping_name = $data['shipping_name'];
            $order->shipping_phone = $data['shipping_phone'];
            $order->shipping_address = $data['shipping_address'];
            $order->remark = $data['remark'] ?? '';
            $order->status = 0; // 待付款
            $order->pay_status = 0; // 未支付
            
            $totalAmount = 0;
            
            // 创建订单商品
            foreach ($data['items'] as $item) {
                $sku = ProductSkuModel::find($item['sku_id']);
                if (!$sku) {
                    throw new BusinessException('商品SKU不存在');
                }
                
                // 检查库存
                if ($sku->stock < $item['quantity']) {
                    throw new BusinessException('商品库存不足');
                }
                
                $product = ProductModel::find($sku->product_id);
                if (!$product) {
                    throw new BusinessException('商品不存在');
                }
                
                $orderItem = new OrderItemModel();
                $orderItem->product_id = $product->id;
                $orderItem->product_sku_id = $sku->id;
                $orderItem->product_name = $product->name;
                $orderItem->product_image = $product->image;
                $orderItem->product_price = $sku->price;
                $orderItem->quantity = $item['quantity'];
                $orderItem->total_amount = $sku->price * $item['quantity'];
                $orderItem->sku_properties = json_encode($sku->properties);
                
                $totalAmount += $orderItem->total_amount;
                
                // 扣减库存
                $sku->decrement('stock', $item['quantity']);
                
                $order->items()->save($orderItem);
            }
            
            $order->total_amount = $totalAmount;
            $order->pay_amount = $totalAmount; // 实际支付金额，可以根据优惠券等进行计算
            $order->save();
            
            \DB::commit();
            
            return json(['code' => 0, 'msg' => '创建订单成功', 'data' => $order]);
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new BusinessException($e->getMessage());
        }
    }
    
    /**
     * 订单列表
     */
    public function list(Request $request)
    {
        $user = $request->user;
        $status = $request->get('status');
        $page = $request->get('page', 1);
        $pageSize = $request->get('page_size', 10);
        
        $query = OrderModel::with('items')
            ->where('user_id', $user->id);
            
        if ($status !== null) {
            $query->where('status', $status);
        }
        
        $orders = $query->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page);
            
        return json(['code' => 0, 'msg' => 'success', 'data' => $orders]);
    }
    
    /**
     * 订单详情
     */
    public function detail(Request $request, $id)
    {
        $user = $request->user;
        $order = OrderModel::with('items')
            ->where('user_id', $user->id)
            ->find($id);
            
        if (!$order) {
            throw new BusinessException('订单不存在');
        }
        
        return json(['code' => 0, 'msg' => 'success', 'data' => $order]);
    }
    
    /**
     * 取消订单
     */
    public function cancel(Request $request, $id)
    {
        $user = $request->user;
        $order = OrderModel::where('user_id', $user->id)
            ->where('status', 0) // 只能取消待付款订单
            ->find($id);
            
        if (!$order) {
            throw new BusinessException('订单不存在或无法取消');
        }
        
        try {
            \DB::beginTransaction();
            
            // 修改订单状态
            $order->status = 4; // 已取消
            $order->save();
            
            // 恢复库存
            foreach ($order->items as $item) {
                ProductSkuModel::where('id', $item->product_sku_id)
                    ->increment('stock', $item->quantity);
            }
            
            \DB::commit();
            
            return json(['code' => 0, 'msg' => '取消订单成功']);
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new BusinessException($e->getMessage());
        }
    }
    
    /**
     * 确认收货
     */
    public function confirm(Request $request, $id)
    {
        $user = $request->user;
        $order = OrderModel::where('user_id', $user->id)
            ->where('status', 2) // 已发货待收货
            ->find($id);
            
        if (!$order) {
            throw new BusinessException('订单不存在或无法确认收货');
        }
        
        $order->status = 3; // 已完成
        $order->save();
        
        return json(['code' => 0, 'msg' => '确认收货成功']);
    }
    
    /**
     * 生成订单号
     */
    private function generateOrderNo()
    {
        return date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }
    
    /**
     * 验证订单数据
     */
    private function validateOrderData($data)
    {
        if (empty($data['shipping_name'])) {
            throw new BusinessException('收货人姓名不能为空');
        }
        if (empty($data['shipping_phone'])) {
            throw new BusinessException('收货人电话不能为空');
        }
        if (empty($data['shipping_address'])) {
            throw new BusinessException('收货地址不能为空');
        }
        if (empty($data['items']) || !is_array($data['items'])) {
            throw new BusinessException('订单商品不能为空');
        }
        foreach ($data['items'] as $item) {
            if (empty($item['sku_id'])) {
                throw new BusinessException('商品SKU不能为空');
            }
            if (empty($item['quantity']) || $item['quantity'] < 1) {
                throw new BusinessException('商品数量必须大于0');
            }
        }
    }

    /**
     * @Apidoc\Title("申请退款")
     * @Apidoc\Method("POST")
     * @Apidoc\Url("/api/order/refund/apply/{id}")
     * @Apidoc\Param("id", type="int", require=true, desc="订单ID")
     * @Apidoc\ParamType("json")
     * @Apidoc\Param("refund_amount", type="number", require=true, desc="退款金额")
     * @Apidoc\Param("refund_reason", type="string", require=true, desc="退款原因")
     * @Apidoc\Param("refund_evidence", type="array", desc="退款凭证图片")
     */
    public function refundApply(Request $request, $id)
    {
        $user = $request->user;
        $data = $request->post();
        
        try {
            // 验证订单是否存在且属于当前用户
            $order = OrderModel::where('user_id', $user->id)
                ->whereIn('status', [1, 2]) // 已付款待发货或已发货待收货
                ->where('refund_status', 0) // 未退款
                ->find($id);
                
            if (!$order) {
                throw new BusinessException('订单不存在或无法申请退款');
            }
            
            // 验证退款金额
            if ($data['refund_amount'] <= 0 || $data['refund_amount'] > $order->pay_amount) {
                throw new BusinessException('退款金额不正确');
            }
            
            // 验证退款原因
            if (empty($data['refund_reason'])) {
                throw new BusinessException('退款原因不能为空');
            }
            
            \DB::beginTransaction();
            
            // 创建退款记录
            $refund = new OrderRefundModel();
            $refund->order_id = $order->id;
            $refund->user_id = $user->id;
            $refund->refund_no = $this->generateRefundNo();
            $refund->refund_amount = $data['refund_amount'];
            $refund->refund_reason = $data['refund_reason'];
            $refund->refund_evidence = $data['refund_evidence'] ?? [];
            $refund->status = 0; // 待处理
            $refund->save();
            
            // 修改订单退款状态
            $order->refund_status = 1; // 退款中
            $order->save();
            
            \DB::commit();
            
            return json(['code' => 0, 'msg' => '申请退款成功', 'data' => $refund]);
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new BusinessException($e->getMessage());
        }
    }
    
    /**
     * @Apidoc\Title("获取退款列表")
     * @Apidoc\Method("GET")
     * @Apidoc\Url("/api/order/refund/list")
     * @Apidoc\Param("page", type="int", default=1, desc="页码")
     * @Apidoc\Param("page_size", type="int", default=10, desc="每页数量")
     * @Apidoc\Param("status", type="int", desc="退款状态")
     */
    public function refundList(Request $request)
    {
        $user = $request->user;
        $status = $request->get('status');
        $page = $request->get('page', 1);
        $pageSize = $request->get('page_size', 10);
        
        $query = OrderRefundModel::with(['order'])
            ->where('user_id', $user->id);
            
        if ($status !== null) {
            $query->where('status', $status);
        }
        
        $refunds = $query->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page);
            
        return json(['code' => 0, 'msg' => 'success', 'data' => $refunds]);
    }
    
    /**
     * @Apidoc\Title("获取退款详情")
     * @Apidoc\Method("GET")
     * @Apidoc\Url("/api/order/refund/detail/{id}")
     * @Apidoc\Param("id", type="int", require=true, desc="退款记录ID")
     */
    public function refundDetail(Request $request, $id)
    {
        $user = $request->user;
        $refund = OrderRefundModel::with(['order'])
            ->where('user_id', $user->id)
            ->find($id);
            
        if (!$refund) {
            throw new BusinessException('退款记录不存在');
        }
        
        return json(['code' => 0, 'msg' => 'success', 'data' => $refund]);
    }
    
    /**
     * 生成退款编号
     */
    private function generateRefundNo()
    {
        return 'RF' . date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }
} 